<script>
	import {
		cloudmateURL,
		appKey
	} from '@/utils/requestURL.js'
	import {
		database,
	} from '@/utils/sql/sqlUser.js'
	import {
		getOffMoney,
		delOffMoney
	} from '@/utils/sql/sqloffLineDtoList.js'
	import {
		getInCome,
		delInCome
	} from '@/utils/sql/sqlInComeDtoList.js'
	import {
		delTrunOver,
		getTrunOver
	} from '@/utils/sql/sqlTrunoverDtoList.js'
	import {
		leaSyn,
		leasebdatas
	} from '@/api/leaData.js'
	import {
		encryption,
		getWeekDate,
		getMonthDate,
		setSyncDevice
	} from '@/utils/index.js'
	import {
		getNoSyncLease,
		setSyncDate,
		getLease
	} from '@/utils/sql/sqllease.js'
	import {
		getUserAll
	} from '@/utils/sql/sqlUser.js'
	import {
		getPassConfig,
		delDBpassConfig
	} from '@/utils/sql/sqlPassConfig.js'
	import {
		getInStoreArr,
	} from '@/utils/sql/sqlDevice.js'
	import {
		liststockbind
	} from '@/api/deviceList.js'
	import {
		delLeasePid
	} from '@/utils/sql/sqllease.js'
	import {
		delPid
	} from '@/utils/sql/sqlDevice.js'
	import {
		reduceInsoter,
		reduceTenantable
	} from '@/utils/sql/sqlDeviceType.js'
	import {
		getMoneyInfo
	} from '@/utils/sql/sqlMoney.js'
	let syncHighTime = null;
	let syncLowTime = null;
	export default {

		async onShow() {
			let isNoNetWork = false
			let that = this
			uni.setStorageSync('platform', uni.getSystemInfoSync().platform)
			// 监听网络网络变化
			uni.getNetworkType({
				success: async res => {
					console.log(res);
					if (res.networkType == 'none') {
						isNoNetWork = true
						console.log(isNoNetWork);
						uni.setStorageSync('isNetWork',isNoNetWork);
					} else {
						isNoNetWork = false
						console.log(isNoNetWork);
						uni.setStorageSync('isNetWork',isNoNetWork);
					}
				},

			})

			// 监听网络变化
			uni.onNetworkStatusChange(async function(res) {
				console.log(res);
				if (!res.isConnected) {
					isNoNetWork = true
					console.log(isNoNetWork);
					uni.setStorageSync('isNetWork',isNoNetWork);
				} else {
					isNoNetWork = false
					console.log(isNoNetWork);
					uni.setStorageSync('isNetWork',isNoNetWork);
				}
			});
			
			// this.$store.commit("setNetWork", isNoNetWork);
			console.log(isNoNetWork);
			uni.setStorageSync('isNetWork',isNoNetWork);

			if (syncHighTime) {
				clearInterval(syncHighTime);
			}
			if (syncLowTime) {
				clearInterval(syncLowTime);
			}

			syncHighTime = setInterval(async () => {

				let accessTokenText = uni.getStorageSync('accessToken');
				if (!accessTokenText || isNoNetWork) return false;
				console.log('同步数据');
				await that.syncMoney();
				await that.syncPass();
			}, 1000 * 60 * 5)

			syncLowTime = setInterval(async () => {
				const now = new Date();
				const hours = now.getHours(); // 获取当前小时
				const minutes = now.getMinutes();

				let accessTokenText = uni.getStorageSync('accessToken');
				if (!accessTokenText || isNoNetWork) return false

				if ([10, 12, 16, 18, 22].includes(hours) && minutes == 0) {
					await that.syncMoney()
					await that.syncPass()
				}

			}, 1000 * 60)

		},
		async onHide() {
			if (syncHighTime) {
				clearInterval(syncHighTime);
			}
			if (syncLowTime) {
				clearInterval(syncLowTime);
			}
			// 关闭数据库
			// 取消监听网络请求
			uni.offNetworkStatusChange(function(res) {
				console.log(res);
			})
	
		},
		methods: {
			async syncDeviceInfo() {
				let res4 = await getNoSyncLease();
				let res4Len = res4.data.length;
				if (res4Len == 0) { //只有本地没有要同步的数据才会同步云端设备

					let dbRes = await getInStoreArr();
					let serRes = await liststockbind();

					let dbArr = dbRes.data == null ? [] : dbRes.data
					let serArr = serRes.data == null ? [] : serRes.data
					console.log(dbArr);
					console.log(serRes);

					let filteredArr = dbArr.filter(dbItem => {
						return !serArr.some(serveItem => {
							return serveItem.productId === dbItem.productId;
						});
					});
					console.log(filteredArr);
					filteredArr.forEach(async item => {
						if (item.stockStatus == 4 || item.stockStatus == 6 || item.stockStatus == 8 || item.stockStatus ==
							10) { //本地多余的数据状态 如果是租赁总或者逾期 去除lease表中的数据
							await delLeasePid(item.productId)
						}
						await delPid(item.productId)

						if (item.stockStatus == 1) { //修改可以租赁的值
							await reduceInsoter(item.productModel);
							await reduceTenantable(item.productModel);
						}

					})
				}

			},
			// 同步完成之后，删除本地金额数据
			delSqlMoney() {
				delOffMoney()
				delInCome()
				delTrunOver()
			},
			syncPass() {
				getPassConfig().then(res => {
					let syncData = {
						"synOpe": "sec",
						data: res.data
					}
					console.log(res);
					leaSyn({
						edata: encryption(JSON.stringify(syncData))
					}).then(res => {
						console.log(res);
						if (res.code == 0) {
							delDBpassConfig()
						}
					})

				})
			},
			async syncLease() {
				let res = await getLease();

				let newArr = res.data.filter(item => {
					// return !(item.leaseStatus == 1 && item.iSync == 1) && item.iSync != 'null'
					return !(item.leaseStatus == 1) && item.iSync != 'null'
				})
				console.log('============', newArr);
				if (newArr.length > 0) {
					let syncData = {
						"data": newArr,
						"synOpe": "local"
					}
					console.log(syncData);
					leaSyn({
						edata: encryption(JSON.stringify(syncData))
					}).then(leRes => {
						console.log(leRes);
						// uni.hideLoading();
						// uni.showToast({
						// 	title: this.$t('me.SyncDevicesucc'),
						// 	icon: 'success'
						// })

					})
				}


			},
			async syncUser() {
				let res = await getUserAll();
				console.log(res);
				let newArr = res.data.map(item => {
					return {
						customerAccount: item.customerAccount,
						rentNum: item.rentNum,
						overdueNum: item.overdueNum,
						lastTimeRent: item.lastTimeRent
					}
				})

				let syncData = {
					"data": newArr,
					"synOpe": "localUser"
				}
				let leRes = await leaSyn({
					edata: encryption(JSON.stringify(syncData))
				})
				console.log(leRes);

			},
			// 同步设备的 租赁 归还 逾期
			async syncDevice() {
				// 获取所有未同步的数据
				let leaRes = await getNoSyncLease();
				console.log(leaRes);


				let syncArr = setSyncDevice(leaRes.data)
				console.log(syncArr);
				if (syncArr.length == 0) {
					// uni.showToast({
					// 	title: '暂无设备同步数据',
					// 	icon: 'none'
					// })
					this.syncDeviceInfo()
					return false
				}
				// uni.showLoading({
				// 	title: '同步设备中',
				// 	icon: 'loading',
				// })
				let promiseAll = []
				syncArr.forEach(async item => {


					let syncData = {
						data: item,
						"synOpe": "lease"
					}
					promiseAll.push(leaSyn({
						edata: encryption(JSON.stringify(syncData))
					}))
					// 租赁信息变为已经同步了
					setSyncDate(item.pid);

				})
				Promise.all(promiseAll).then(results => {
					let result = results.every(ele => ele.code == 0);
					if (result) {
						this.syncDeviceInfo()
						//从云端同步设备数据下拉，应对设备释放，和在库设备在别的代理商入库
					} else {
						let err = results.find(e => {
							return e.code != 0
						})

					}
				}).catch(error => {
					console.log(error, '错误')
				})

			},
			async syncMoney() { //同步金钱
				// uni.showLoading({
				// 	title: this.$t('me.SyncingData'),
				// 	icon: 'loading',
				// })
				console.log('同步金额');
				let offRes = await getOffMoney();
				let inRes = await getInCome();
				let overRes = await getTrunOver();
				let mRes = await getMoneyInfo();
				console.log(mRes);
				let syncData = {
					data: {
						"amountIncome": null,
						"amountOffline": null,
						"amountTurnover": null,
						synAmountIncomeDtoList: null,
						synAmountOfflineDtoList: null,
						synAmountTurnoverDtoList: null,
					},
					"synOpe": "amount"
				}

				if (offRes.data.length > 0) {
					let offResLen = offRes.data.length - 1;
					// syncData.data.amountOffline = offRes.data[offResLen].offlineAmountAll;
					syncData.data.amountOffline = mRes.data[0].offMoney;
					syncData.data.synAmountOfflineDtoList = offRes.data
				}

				if (inRes.data.length > 0) {
					let inResLen = inRes.data.length - 1;
					// syncData.data.amountIncome = inRes.data[inResLen].incomeAmountAll;
					syncData.data.amountIncome = mRes.data[0].amountIncome;
					syncData.data.synAmountIncomeDtoList = inRes.data
				}

				if (overRes.data.length > 0) {
					let overResLen = overRes.data.length - 1;
					// syncData.data.amountTurnover = overRes.data[overResLen].turnoverAmountAll;
					syncData.data.amountTurnover = mRes.data[0].amountTurnover;
					syncData.data.synAmountTurnoverDtoList = overRes.data
				}


				let res = await leaSyn({
					edata: encryption(JSON.stringify(syncData))
				})
				console.log(res);
				if (res.code == 0) {

					this.delSqlMoney()
					setTimeout(() => {
						// uni.hideLoading();
						// uni.showToast({
						// 	title: '同步金额成功',
						// 	icon: 'success'
						// })

						setTimeout(() => {
							this.syncDevice()
						}, 1000)
					}, 1000)


				} else {
					// setTimeout(() => {
					// 	uni.hideLoading();
					// 	uni.showToast({
					// 		title: res.msg,
					// 		icon: 'error'
					// 	})
					// }, 1000)

				}
			},
		},
		computed: {
			i18n() {
				return this.$t('index')
			}
		}
	}
</script>
<style lang="scss">
	/* #ifndef APP-PLUS-NVUE */


	page {
		width: 100%;
		height: 100%;
		color: var(--subjectTextColor);

		// 弱文字提示
		.minorTest {
			color: var(--subtopicNextTextColor);
			font-size: 14px;
		}

		.uni-app--showleftwindow+.uni-tabbar-bottom {
			display: none;
		}

		.offLineStatus {
			opacity: 0.5;
		}

		// flex 布局
		.flex-c-SB {
			display: flex;
			align-items: center;
			justify-content: space-between;
		}

		.flex-c-SB-c {
			display: flex;
			align-items: center;
			justify-content: space-between;
			flex-direction: column;
		}

		.flex-c-SE-c {
			display: flex;
			align-items: center;
			justify-content: space-evenly;
			flex-direction: column;
		}

		// slider组件
		.mySlider {
			/deep/.fui-slider__pole {
				border: 1px solid var(--borderColor);
				box-sizing: border-box;
			}

			/deep/.fui-slider__pole-left {
				transform: scale(1.1) !important;
				transform: translateX(10px);
			}
		}

		.flex-center {
			display: flex;
			align-items: center;
			justify-content: center;
		}

		.content {
			// background-color: var(--backSubject);
			background-color: #f8f8f8;
			color: var(--subjectTextColor);
			width: 100%;
			height: 100%;


			// icon 主题色
			.subIconColor {
				color: var(--subjectColor);
			}

			// 普通icon 
			.subtopicIconColor {
				color: var(--subtopicTextColor);
			}

			// 按钮样式
			/deep/.u-button {
				height: 44px;
				font-size: 17px;
			}

			// popup 弹框组件
			.popupContent {
				/deep/.u-safe-area-inset-bottom {
					padding: 0 !important;
				}
			}

			// 卡片
			.myCard {
				background: var(--moduleColor);
				box-shadow: 0px 0px 4px var(--smallBoxShadow);
				border-radius: 8px;
			}

			// form表单 
			.myForm {
				/deep/.u-form-item {
					// height: 41px;
					// margin-bottom: 16px;
				}

				/deep/.u-form-item__body__right__message {
					margin-left: 0 !important;
					margin-top: 8px;
				}

				/deep/.u-form-item__body {
					padding: 0 !important;
				}

				/deep/.u-input__content__clear {
					color: var(--subtopicTextColor) !important;
					font-size: 18px;
				}

			}

			// cell 组件
			.myCell {
				margin-top: 8px;

				/deep/.u-cell-group {
					background-color: var(--moduleColor);

					.u-cell {
						height: 52px;

						.u-cell__body {
							height: 52px;

							.u-cell__title-text {
								color: var(--subjectTextColor);
								font-size: 17px;
								width: 200px;
								display: block;
								white-space: nowrap;
								overflow: hidden;
								text-overflow: ellipsis;
							}

							.u-cell__value {
								color: var(--subtopicNextTextColor);
								font-size: 14px;
								width: 200px;
								display: block;
								white-space: nowrap;
								overflow: hidden;
								text-overflow: ellipsis;
							}

							.u-icon {
								font-size: 18px;
								color: var(--subtopicTextColor);
							}
						}
					}
				}
			}

			//sheet样式 使用 sheet组件在组件外加一层盒子 命名为 mySheet
			// .mySheet {
			// 	/deep/.u-action-sheet {
			// 		background-color: var(--moduleColor);
			// 		border-radius: 16px;
			// 	}

			// 	/deep/.u-safe-bottom {
			// 		padding-bottom: 0 !important;
			// 	}

			// 	/deep/.u-reset-button {
			// 		height: 58px;
			// 	}

			// 	/deep/.u-popup__content {
			// 		background-color: var(--moduleColor);
			// 		width: calc(100% - 32px);
			// 		margin: 0 auto 16px;
			// 		border-radius: 16px;
			// 		padding: 16px 0;
			// 	}

			// 	/deep/.u-gap {
			// 		height: 1px !important;
			// 		background-color: var(--borderColor) !important;
			// 	}

			// 	/deep/.u-action-sheet__cancel-text {
			// 		color: var(--subtopicTextColor) !important;
			// 		font-size: 17px !important;
			// 	}
			// }
		}
	}

	@import "uview-ui/index.scss";
	@import "static/iconfont/iconfont.css"
	/* #endif */
</style>